
<template>
  <div class="chat-room">
    <h1>聊天室</h1>
    <div class="user-controls">
      <!-- 显示当前用户的用户名 -->
      <input type="text" v-model="sendOutUser" placeholder="自己的用户名" ref="sendOutUser" />
      <!-- 连接 WebSocket 按钮 -->
      <button @click="connectWebSocket">上线</button>
      <!-- 关闭 WebSocket 连接按钮 -->
      <button @click="closeWebSocket">下线</button>
      <!-- 显示未读消息数量 -->
      <span v-if="unreadCount > 0" class="unread-count">{{ unreadCount }} 未读消息</span>
    </div>

    <div class="message-input">
      <!-- 输入要发送的消息 -->
      <input type="text" v-model="msg" placeholder="要发送的信息" />
      <!-- 显示接收人的用户名,这里设置为只读 -->
      <input type="text" v-model="receiveUser" placeholder="接收人的用户名" disabled />
      <!-- 发送消息按钮 -->
      <button @click="send">发送</button>
    </div>

    <!-- 如果用户角色不是 4 或 '4', 显示接单按钮 -->
    <div class="message-input" v-if="RoleId !== 4 && RoleId !== '4'">
      <input type="text" v-model="orderId" placeholder="接受的工单id" />
      <button @click="updateOrderStarer">接单</button>
    </div>

    <!-- 如果正在进行对话, 显示结束对话按钮 -->
    <div class="message-input" v-if="Conversation">
      <button @click="finishConversation">结束沟通</button>
    </div>

    <!-- 如果有问题图片, 显示查看按钮 -->
    <template v-if="isImg">
      <el-button style="width: 120px;" type="text" @click="open">查看问题图片</el-button>
    </template>

    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="dialogVisible" width="50%">
      <img :src="imageSrc" alt="问题图片" v-if="imageSrc" style="width: 100%; height: auto;" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>

    <hr />

    <!-- 显示聊天消息列表 -->
    <div class="msg-list">
      <div v-for="(msg, index) in msgList" :key="index" class="msg">{{ msg }}</div>
    </div>

    <!-- 如果问题已解决, 显示"问题以解决"按钮 -->
    <div v-if="IssBuu"><el-button style="width: 120px;" type="text" @click="onlineProblemSolving">问题以解决</el-button></div>

    <!-- 如果可以转线下处理, 显示转线下处理按钮 -->
    <div>
      <el-button v-if="transferOffline" style="width: 130px;" type="text" @click="openTransferDialog">转线下处理</el-button>
    </div>

  <div>
    <el-dialog title="评价问题解决" :visible.sync="rateDialogVisible" width="30%">
      <div style="text-align: center;">
        请为问题解决情况评分:
        <el-rate v-model="userRating" :colors="['#99A9BF', '#F7BA2A', '#FF9900']"></el-rate>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="submitRating">提交</el-button>
        <el-button @click="rateDialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>


    <!-- 转线下处理对话框 -->
    <el-dialog title="转线下处理" :visible.sync="showTransferDialog" width="30%">
      <div class="input-container">
        <input type="text" v-model="transferAddress" placeholder="请输入预约处理地址" />
       <el-date-picker
         v-model="transferDate"
         type="datetime"
         placeholder="选择日期和时间"
         style="width: 100%;"
         :disabled-date="disabledDate"
       >
       </el-date-picker>
        <el-table :data="staffList" style="width: 100%">
          <el-table-column prop="accountId" label="id"></el-table-column>
          <el-table-column prop="name" label="姓名"></el-table-column>
          <el-table-column label="随行人员选择">
            <template slot-scope="scope">
              <el-checkbox v-model="scope.row.selected"
                :disabled="selectedCompinionsCount >= 3 && !scope.row.selected"  >选择</el-checkbox>
            </template>
          </el-table-column>
        </el-table>
        <el-button type="primary" @click="confirmTransferOffline">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "ChatRoom",
  data() {
    return {
      websocket: null, // WebSocket 连接对象
      sendOutUser: '', // 当前用户的用户名
      msg: '', // 要发送的消息
      receiveUser: '', // 接收人的用户名
      msgList: [], // 聊天消息列表
      unreadCount: 0, // 未读消息数量
      orderId: '', // 工单号
      RoleId: '', // 当前用户的角色 ID
      isImg: false, // 是否有问题图片
      imageSrc: '', // 问题图片的 URL
      dialogVisible: false, // 图片预览对话框是否可见
      Conversation: false, // 是否正在进行对话
      IssBuu: false, // 问题是否已解决
      adminButton: false, // 是否显示管理员按钮
      transferOffline: false, // 是否可以转线下处理
      showTransferDialog: false, // 转线下处理对话框是否可见
      transferAddress: '', // 转线下处理的地址
      transferDate: '', // 转线下处理的日期
      staffList: [] ,// 随行人员列表
      selectedCompinionsCount: 0, // 已选择的随行人员数量
      rateDialogVisible:false,
      userRating: 0 ,// 新增: 存储用户评分
    };
  },
  methods: {
    finishConversation(){
      this.$router.go(-1);
    },
    submitRating(){
      console.log(this.userRating)
      const formData = new FormData();
      formData.append('score',this.userRating);
      this.$http.post('/tWorkOrder/Score',formData)
        .then(response => {
          console.log(response);
           this.rateDialogVisible = false;
        })
        .catch(error => {
          console.error(error);
        });
    },
    onlineProblemSolving(){
      this.$http.post('/tWorkOrder/onlineProblemSolving')
        .then(response => {
          console.log(response);
          if(this.RoleId==4){
             this.rateDialogVisible = true; // 显示评分对话框
          }
        })
        .catch(error => {
          console.error(error);
        });
    },

    // 打开转线下处理对话框
    openTransferDialog() {

      this.$http.post('/tAgent/selectCompinion')
        .then(response => {
          console.log(response);
          this.staffList=response.data.data;
        })
        .catch(error => {
          console.error(error);
        });
      this.showTransferDialog = true;

    },
    // 禁用之前的日期
    disabledDate(time) {
           return date.getDay() === 0 || date.getDay() === 6 || date < new Date();
        },
    // 确认转线下处理
    confirmTransferOffline() {
if (this.transferAddress === '') {
        this.$message.error('请输入地址');
        return;
      }

      // 过滤出已选择的随行人员
            const selectedCompinions = this.staffList.filter(staff => staff.selected);

            // 检查选择的随行人员数量是否在 1 到 3 个之间
            if (selectedCompinions.length < 1 || selectedCompinions.length > 3) {
              this.$message.error('请选择 1 到 3 个随行人员');
              return;
            }


      const formData = new FormData();
       const selectedCompinionIds = selectedCompinions.map(staff => staff.accountId);
      formData.append('orderNo', this.orderId);
      formData.append('checkAddress', this.transferAddress);
      // 转换 transferDate 为字符串格式（如需要不同格式可以在这里调整）
       const checkTime = this.transferDate ? new Date(this.transferDate).toISOString().slice(0, 19) : ''; // yyyy-MM-ddTHH:mm:ss 格式
       formData.append('checkTime', checkTime);

      formData.append('accompanyIds', JSON.stringify(selectedCompinionIds));
      console.log(checkTime)

      this.$http.post('/tWorkOrder/transferOffline', formData)
        .then(response => {
          this.$message.success('转线下处理成功');
          this.showTransferDialog = false;
          this.transferAddress = '';
          this.transferDate = null;
          this.staffList = [];
        })
        .catch(error => {
          this.$message.error('转线下处理失败');
          console.error(error);
        });
    },
    // 结束对话
    finishConversation() {
      this.receiveUser = '';
      this.$http.post('/WebSocket/finishConversation')
        .then(response => {
          console.log(response);
        })
        .catch(error => {
          console.error(error);
        });
    },
    // 打开问题图片预览
    open() {
      if (!this.orderId) {
        this.$message.error('请输入工单号以获取相关图片');
        return;
      }

      const formData = new FormData();
      formData.append('orderId', this.orderId);

      this.$http.post('/tIssue/selectIssueImage', formData)
        .then(response => {
          console.log(response);
          this.imageSrc = response.data.data;
          this.dialogVisible = true;
        })
        .catch(error => {
          console.error(error);
          this.$message.error('获取图片失败，请稍后再试');
        });
    },
    // 获取当前用户的角色 ID
    selectRoleId() {
      this.$http.post('/tAccount/selectRoleId')
        .then(resp => {
          this.RoleId = resp.data.data;
        });
    },
    // 接受工单
    updateOrderStarer() {
      if (!this.orderId) {
        alert("请输入需要接受的工单号");
        return;
      }
      const orderIdNumber = this.orderId;
      const formData = new FormData();
      formData.append('orderIdNumber', orderIdNumber);
      console.log("订单号：" + orderIdNumber)
      this.$http.post('/tWorkOrder/updateOrderStaterBySocket', formData)
        .then(resp => {
          console.log(resp);
          this.receiveUser = resp.data.data;
          this.isImg = !!this.receiveUser;
        });
    },
    // 连接 WebSocket
    connectWebSocket() {
      // 获取当前连接人的姓名
      if (this.RoleId == 4 && this.RoleId == '4') {
        this.$http.post('/WebSocket/getTheNameOfTheChat')
          .then(resp => {
            if (this.receiveUser == '' || this.receiveUser == null) {
              this.receiveUser = resp.data.data;
            }
          })
          .catch(error => {
            console.error(error);
          });
      } else if (this.RoleId !== 4 && this.receiveUser == '' || this.receiveUser == null) {
        this.$http.post('/WebSocket/KtpGetTheNameOfTheChat')
          .then(resp => {
            if (this.receiveUser == '' || this.receiveUser == null) {
              this.receiveUser = resp.data.data;
            }
          })
          .catch(error => {
            console.error(error);
          });
      }

      this.sendOutUser = localStorage.getItem('currentAccountName');
      if ('WebSocket' in window) {
        const token = localStorage.getItem("token");
        this.websocket = new WebSocket("ws://localhost:8877/web-socket/" + token);

        this.websocket.onerror = () => {
          alert("连接发生错误");
        };

        this.websocket.onopen = () => {
          this.$refs.sendOutUser.readOnly = true;
          this.$refs.sendOutUser.style.backgroundColor = '#ddd';
        };

        this.websocket.onmessage = (event) => {
          if (event.data.startsWith("未处理的工单:")) {
            const workOrderJson = event.data.replace("未处理的工单: ", "");
            const workOrder = JSON.parse(workOrderJson);
            this.msgList.push(`未读工单: ID ${workOrder.orderId}, 内容: ${workOrder.description}, 状态: ${workOrder.status}`);
            this.$message({
              message: `您有新的未读工单: ID ${workOrder.orderId}, 内容: ${workOrder.description}, 状态: ${workOrder.status}`,
              type: 'info'
            });
          } else if (event.data.startsWith("未读消息:")) {
            this.unreadCount += 1;
            this.msgList.push(event.data);
          } else {
            this.msgList.push(event.data);
          }
        };

        this.websocket.onclose = () => {
          this.msgList.push("websocket连接关闭");
        };

        window.onbeforeunload = () => {
          this.closeWebSocket();
        };
      } else {
        alert('当前浏览器不支持 websocket');
      }
    },
    // 关闭 WebSocket 连接
    closeWebSocket() {
      if (this.websocket) {
        this.websocket.close();
      }
    },
    // 发送消息
    send() {
      // 根据用户角色设置相关状态
      if (this.RoleId == 1 || this.RoleId == '1') {
        this.adminButton = true;
      }
      if (this.RoleId == 3) {
        this.transferOffline = true;
      }
      if (this.RoleId == 4) {
        this.IssBuu = true;
      }

      if (this.msg === "") {
        alert("请输入消息");
        return;
      }

      const m = new Map();
      m.set("sendOutUser", this.sendOutUser);
      m.set("msg", this.msg);

      if (this.receiveUser === "") {
        m.set("type", 0);
      } else {
        m.set("receiveUser", this.receiveUser);
        m.set("type", 1);
      }

      const json = this.mapToJson(m);
      this.websocket.send(json);
      this.msgList.push("我: " + this.msg);
      this.msg = '';
      if (this.RoleId !== 4 && this.RoleId !== '4') {
        this.Conversation = true;
      }
    },
    // 将 Map 转换为 JSON 字符串
    mapToJson(map) {
      const obj = Object.create(null);
      for (const [k, v] of map) {
        obj[k] = v;
      }
      return JSON.stringify(obj);
    }
  },
  created() {
    this.selectRoleId();
  }
};
</script>

<style scoped>
.chat-room {
  max-width: 800px;
  margin: 30px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: #f9f9f9;
}

h1 {
  text-align: center;
  font-size: 24px;
  color: #333;
}

.user-controls {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.message-input {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

input {
  width: 150px;
  height: 30px;
  line-height: 25px;
  padding: 5px 10px;
  border-radius: 5px;
  border: 2px solid #ccc;
  font-size: 16px;
  margin-right: 10px;
}

button {
  width: 80px;
  height: 36px;
  padding: 5px 10px;
  border-radius: 5px;
  background-color: #5cb85c;
  color: white;
  border: none;
  cursor: pointer;
  transition: background-color 0.3s;
}

button:hover {
  background-color: #4cae4c;
}

.unread-count {
  margin-left: 10px;
  color: red;
  font-weight: bold;
}

hr {
  margin: 20px 0;
}

.msg-list {
  max-height: 300px;
  overflow-y: auto;
  border: 1px solid #e1e1e1;
  border-radius: 5px;
  padding: 10px;
  background: white;
}

.msg {
  padding: 5px;
  margin: 5px 0;
  border-radius: 5px;
  background-color: #e7f3fe;
  color: #31708f;
  word-wrap: break-word;
}
</style>
